<?php 
namespace app\task\controller;
use app\common\lib\WxTemplateMsg;
use app\common\model\BaiduToken;
use app\common\model\GptToken;
use app\common\model\MemberPointsLog;
use think\facade\App;
use app\BaseController;
use GuzzleHttp\Client;
use think\facade\Db;
//这个控制器专门用于测试的
class Test extends BaseController{
    const API_KEY = "OA3UUn39OSbOZCvW8uoyxGZq";
    const SECRET_KEY = "LjGDA04LmR6KnQ37XKGsRa29cKBOOAIC";
    public function test(){
        // 创建一个GuzzleHttp的Client实例
        $client = new Client();

        // 请求的URL
        $url = 'https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernie/3.0.25/zeus';

        // 请求的参数（如果有的话）
        $data = [
            'access_token' => $this->getAccessToken(),
            'async' => 1,
            'typeId' => 1,
            'text' => '你好',
            'seq_len' => 256,
            'task_prompt' => 'qa',
            'penalty_score' => 1,2,
            'dataset_prompt' => 'qa',
            'is_unidirectional' => 0,
            'min_dec_len' => 2,
            'min_dec_penalty_text' =>  "。?：！[<S>]",
            'mask_type' => 'word',
            'topp"' => 0.8
        ];

        try {
            // 发起POST请求
            $response = $client->request('POST', $url, [
                'form_params' => $data // 使用form_params选项发送POST数据
            ]);

            // 获取响应的内容
            $body = $response->getBody();

            // 将JSON响应转换为数组（如果服务器返回的是JSON数据）
            $result = json_decode($body, true);

            // 处理响应结果
            dump($result);
        } catch (Exception $e) {
            // 捕获异常，处理请求失败的情况
            echo 'Caught exception: ', $e->getMessage(), "\n";
        }
    }

    public static function chat($msg="生成10个关于'百家号推广'的文章标题,结果以如下格式返回，每行一个", $stream = false, $event_name = '', $returnLine = true, $event_handle = false,$is_json = true)
    {
        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => config('transfer.python_address'),
            'timeout' => 80,
        ]);

//        $token = GptToken::where('id' ,'=', 1)->value('token');
        $tokenModel = GptToken::order('update_time', 'asc')->where('id', '>', 0)->find();
        $token = $tokenModel['token'];
        $tokenModel->force()->save();


        header('X-Accel-Buffering: no');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        //跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');

        set_time_limit(0); //防止超时
        ob_end_clean();
        ob_implicit_flush(1);



        try {
            $tokenModel = BaiduToken::order('update_time', 'asc')->where('id', '>', 0)->find();
            $tokenModel->force()->save();

            $res = $client->request('post', '/baidu_chat', [
                'stream' => true,
                'verify' => false,
                'json' => [
                    'query' => $msg,
                    "ak"=>$tokenModel->ak,
                    "sk"=> $tokenModel->sk
                ],
            ]);

        } catch (\Exception $e) {
            $msg = $e->getResponse()->getReasonPhrase();
            $c = "event:{$event_name}" . PHP_EOL; //定义事件
            $c .= "data:" . $msg . PHP_EOL; //推送内容
            echo $c . PHP_EOL;

            $c = "event:{$event_name}" . PHP_EOL; //定义事件
            $c .= "data:end" . PHP_EOL; //推送内容
            echo $c . PHP_EOL;
        }


        $body = $res->getBody();
        $remainder = '';
        $all_res = '';
        while (!$body->eof()) {
            $chunk = $body->read(2);
            echo $chunk;




        }
        exit;
    }

    private function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::API_KEY,
            'client_secret' => self::SECRET_KEY
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
    public function addDog(){

//        $members=Db::name("member")->field("id,chat_end_time")->where("chat_end_time",">","1695809711")->order("id asc")->select()->toArray();
//
//        foreach ($members as $v){
//            //dump($members);exit;
//            //echo $v['chat_end_time'] + 5184000;exit;
//            Db::name("member")->update([
//                'id' => $v['id'],
//                'chat_end_time' => $v['chat_end_time'] + 5184000
//            ]);
//
//            //发送模板消息
//            $result=WxTemplateMsg::send($v['id'],2, [
//                'thing17' => "AIDOG聊天赠送时间",
//                'thing35' => "向您赠送60天，截止时间为".date("Y-m-d",$v['chat_end_time'] + 5184000),
//                'thing4' => "欢迎您登录ai-dog.net使用",
//            ]);
//        }
//        echo "发送成功";
    }

    public function addPoint(){
//        $offset=input("offset");
//        $len=100;
//        // 积分验证
//        $members=Db::name("member")->field("id,point_num")->limit($offset,$len)->order("id asc")->select()->toArray();
//        if(!$members){
//            echo "所有已完成";exit;
//        }
//
//
//        $cost_points = 500;
//        foreach ($members as $v){
//            \app\common\model\Member::update([
//                'id' => $v['id'],
//                'point_num' => $v['point_num'] + $cost_points
//            ]);
//            $point_log = MemberPointsLog::create([
//                'member_id' => $v['id'],
//                'num' => $cost_points,
//                'end_num' => $v['point_num'] + $cost_points,
//                'remarks' => "aidog官方赠送",
//            ]);
//            //发送模板消息
//            $result=WxTemplateMsg::send($v['id'],2, [
//                'thing17' => "AIDOG积分到账",
//                'thing35' => "免费向您赠送500积分",
//                'thing4' => "欢迎您登录ai-dog.net使用",
//            ]);
//        }

        echo "<script>location.href='https://api.ai-dog.net/task/Test/addPoint?offset=".($offset+$len)."'</script>执行完成正在跳转";
    }
}
